<template>
  <el-dialog
    v-dialogDrag
    class="dialogStyleMiddle"
    :title="dialogTitle"
    style="padding:0;"
    :visible="dialogVisible"
    :before-close="cancel"
  >
    <el-form
      v-if="dialogVisible"
      ref="addSysEnterpriseForm"
      :model="sysEnterprise"
      :rules="rules"
      label-width="80px"
    >
      <el-row>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="企业类型" prop="enterpriseType">-->
        <!--            <el-radio-group v-model="sysEnterprise.enterpriseType" size="medium">-->
        <!--              <el-radio label="0">一般企业</el-radio>-->
        <!--              <el-radio label="2">监管单位</el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="企业名称" prop="name">
            <el-input v-model="sysEnterprise.name" placeholder="请输入企业名称" size="medium" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业性质" prop="nature">
            <el-select v-model="sysEnterprise.nature" style="width:100%" size="medium">
              <el-option
                v-for="dict in natureData"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择地址" prop="area" class="distpickerClass">
            <el-cascader
              v-model="selectedOptions"
              :options="options"
              :separator="' '"
              filterable
              clearable
              size="medium"
              style="width: 100%"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="sysEnterprise.address" placeholder="请输入企业详细地址" size="medium" />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item label="企业法人" prop="legalperson">
            <el-input v-model="sysEnterprise.legalperson" placeholder="请输入企业法人" size="medium" />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item label="法人电话" prop="legalpersonMobile">
            <el-input
              v-model="sysEnterprise.legalpersonMobile"
              placeholder="请输入法人电话"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <label slot="label" v-html="`联&ensp;系&ensp;人`" />
            <el-input v-model="sysEnterprise.contacts" placeholder="请输入联系人姓名" size="medium" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="sysEnterprise.phone" placeholder="请输入联系人电话" size="medium" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="sysEnterprise.idNumber" placeholder="请输入联系人身份证号" size="medium" />
          </el-form-item>
        </el-col> -->
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item prop="seller">
            <label slot="label">销售代表</label>
            <el-input
              v-model="sysEnterprise.seller"
              size="medium"
              placeholder="请输入销售代表"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item label="客服代表" prop="counterpart">
            <el-input
              v-model="sysEnterprise.counterpart"
              placeholder="请输入客服代表"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item label="资质证书" prop="qualificationUrl">
            <el-input
              v-model="sysEnterprise.qualificationUrl"
              placeholder="请输入企业资质证书"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="12">
          <el-form-item label="企业信用代码" prop="creditCodePic">
            <el-input
              v-model="sysEnterprise.creditCodePic"
              placeholder="请输入企业信用代码"
              size="medium"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="sysEnterprise.enterpriseType === '0'" :span="24">
          <el-form-item prop="unitCreditCodePicUrl">
            <span slot="label">企业信用&nbsp;&nbsp;&nbsp;&nbsp;<br>代码扫描件</span>
            <!-- <el-input
                v-model="sysEnterprise.unitCreditCodePic"
                placeholder="请输入企业信用代码扫描件"
              ></el-input> -->
            <!-- 附件上传组件 -->
            <file-uplode-no-table ref="fileUplode" style="margin-top:10px;" :edit-file-list="editFileList" :category="category" @getFileIdsList="getFileIdsList" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button size="medium" :disabled="btnDisabled" type="primary" @click="submitForm('addSysEnterpriseForm')">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import options from '@/utils/country-data/country-level3-data'
import { listRegionTree } from '@/api/common/area'
import { updateBasis, addBasis, getBasisById, checkEccUnique } from '@/api/enterprise/basis'
// 附件上传
import FileUplodeNoTable from '@/components/FileUplode/FileUplodeNoTable'
import { selectFileById } from '@/api/file/file.js'
export default {
  name: 'AddBasis',
  components: {
    FileUplodeNoTable
  },
  data() {
    // 信用代码查重校验
    const validcreditCodePic = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('企业信用代码不能为空'))
      } else {
        const id = this.sysEnterprise.id
        const creditCodePic = value
        checkEccUnique(id, creditCodePic).then(resp => {
          if (resp.data === '1') {
            return callback(new Error('企业信用代码已存在，请重新输入'))
          } else {
            callback()
          }
        })
      }
    }
    // 信用代码规范校验
    const checkCodePic = (rule, value, callback) => {
      const reg = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/
      if (!reg.test(value)) {
        return callback(new Error('企业信用代码不符合规范'))
      } else {
        callback()
      }
    }
    return {
      dialogTitle: '',
      dialogVisible: false,
      sysEnterprise: {
        id: '',
        name: '',
        nature: '',
        creditCodePic: '',
        unitCreditCodePicUrl: '',
        fileIds: '',
        qualificationUrl: '',
        province: '',
        city: '',
        area: '',
        address: '',
        legalperson: '',
        legalpersonMobile: '',
        idNumber: '',
        contacts: '',
        phone: '',
        enterpriseType: '2',
        counterpart: '',
        seller: '',
        checkStatus: '2',
        status: ''
      },
      selectedOptions: [],
      options: [],
      natureData: [],
      /** 文件上传 *******start*/
      // 附件分类 (/项目阶段信息)
      category: 'enterpriseBasis',
      editFileList: [],
      // 用于保存附件上传返回的fileIds(Sting逗号分隔)
      fileIdsString: '',
      /** 文件上传 *******end*/
      btnDisabled: false,
      rules: {
        name: [{ required: true, message: '企业名称不得为空', trigger: 'blur' }],
        nature: [{ required: true, message: '必填:企业性质', trigger: 'blur' }],
        area: [{ required: true, message: '必填:省份,城市,县/区域', trigger: 'blur' }],
        address: [
          { required: true, message: '必填:详细地址', trigger: 'blur' }
        ],
        legalperson: [
          { required: true, message: '必填:企业法人', trigger: 'blur' }
        ],
        legalpersonMobile: [
          {
            required: true,
            pattern: /^[1][3-9][0-9]{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        contacts: [
          { required: true, message: '必填:联系人姓名', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '必填:联系人身份证号', trigger: 'blur' },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '身份证号码格式不正确',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            pattern: /^[1][3-9][0-9]{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        enterpriseType: [
          { required: true, message: '必填:企业性质必填', trigger: 'blur' }
        ],
        creditCodePic: [
          { required: true, validator: validcreditCodePic, trigger: 'blur' },
          { required: true, validator: checkCodePic, trigger: 'blur' }
        ],
        counterpart: [
          { required: true, message: '必填:企业对接人必填', trigger: 'blur' }
        ],
        seller: [
          { required: true, message: '必填:销售代表必填', trigger: 'blur' }
        ],
        unitCreditCodePicUrl: [
          { required: true, message: '企业信用代码扫描件不得为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getDicts('enterprise_nature').then(response => {
      this.natureData = response.data.rows
    })
    listRegionTree().then(res => {
      if (res.data) {
        this.options = res.data
      }
    })
  },
  methods: {
    basisItemAdd() {
      this.dialogTitle = '新增企业'
      this.emptySysEnterprise()
      this.dialogVisible = true
    },
    basisItemUpdate(id) {
      this.dialogTitle = '修改企业'
      this.emptySysEnterprise()
      this.getBasis(id)
      this.dialogVisible = true
    },
    handleChange(value) {
      this.sysEnterprise.province = value[0]
      this.sysEnterprise.city = value[1]
      this.sysEnterprise.area = value[2]
      console.log(this.sysEnterprise.area)
    },
    getBasis(id) {
      // 根据id查找这条的内容
      getBasisById(id).then(resp => {
        if (resp) {
          this.dialogTitle = '修改企业'
          const { id, nature, name, creditCodePic, unitCreditCodePicUrl,
            qualificationUrl, province, city, area, address, legalperson, legalpersonMobile,
            idNumber, contacts, phone, enterpriseType, counterpart, seller, status } = resp.data

          this.selectedOptions = [province, city, area]
          this.sysEnterprise = {
            ...this.sysEnterprise,
            id, nature, name, creditCodePic, unitCreditCodePicUrl,
            qualificationUrl, province, city, area, address, legalperson, legalpersonMobile,
            idNumber, contacts, phone, enterpriseType, counterpart, seller, status,
            checkStatus: '2'
          }
          if (this.sysEnterprise.unitCreditCodePicUrl) {
            this.selectFildListByIds(this.sysEnterprise.unitCreditCodePicUrl)
          }
        }
      })
        .catch(() => {
          this.msgError({ message: '修改查找失败！' })
        })
    },
    onSelected(data) {
      this.sysEnterprise.province = data.province.value
      this.sysEnterprise.city = data.city.value
      this.sysEnterprise.area = data.area.value
      data.province = ''
      data.city = ''
      data.area = ''
    },
    /** ************附件上传start*******************/
    // 根据附件id查询附件信息
    selectFildListByIds() {
      const fileIds = this.sysEnterprise.unitCreditCodePicUrl
      selectFileById(fileIds).then(resp => {
        if (resp) {
          this.editFileList = resp.data
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 接受附件子组件 回传过来的附件id
    getFileIdsList(fileIdsList, fileIds) {
      let attachId = ''
      for (let i = 0; i < fileIdsList.length; i++) {
        attachId += fileIdsList[i].fileId + ','
      }
      // 去掉最后一个逗号
      if (attachId.length > 0) {
        attachId = attachId.substr(0, attachId.length - 1)
      }
      this.fileIdsString = attachId
      this.sysEnterprise.unitCreditCodePicUrl = this.fileIdsString
      this.sysEnterprise.fileIds = fileIds
    },
    // 弹框确认按钮
    submitForm(fromData) {
      this.$refs[fromData].validate(valid => {
        if (valid) {
          this.btnDisabled = true
          const id = this.sysEnterprise.id
          this.sysEnterprise.unitCreditCodePicUrl = this.fileIdsString
          if (id) {
            // 更新
            updateBasis(this.sysEnterprise).then(resp => {
              if (resp) {
                if (this.sysEnterprise.enterpriseType === '0') this.$refs.fileUplode.emptyFile()
                this.emptySysEnterprise()
                this.$emit('childrenGetList')
                this.dialogVisible = false
                this.msgSuccess('修改成功')
              } else {
                this.msgError(resp.message)
              }
              this.btnDisabled = false
            })
          } else {
            // 添加
            addBasis(this.sysEnterprise).then(resp => {
              if (resp) {
                if (this.sysEnterprise.enterpriseType === '0') this.$refs.fileUplode.emptyFile()
                this.emptySysEnterprise()
                this.$emit('childrenGetList')
                this.dialogVisible = false
                this.msgSuccess('操作成功')
              } else {
                this.msgError(resp.message)
              }
              this.btnDisabled = false
            })
          }
        } else {
          return false
        }
      })
    },
    // 弹框取消按钮
    cancel() {
      this.sysEnterprise.province = ''
      this.sysEnterprise.city = ''
      this.sysEnterprise.area = ''
      this.emptySysEnterprise()
      if (this.$refs.fileUplode) {
        this.$refs.fileUplode.emptyFile()
        this.$refs.fileUplode.cancelDeleteByID()
      }
      this.$refs.addSysEnterpriseForm.resetFields()
      this.dialogVisible = false
      this.btnDisabled = false
    },
    // 设置提交的值为空
    emptySysEnterprise() {
      this.resetForm('addSysEnterpriseForm')
      this.sysEnterprise.id = ''
      this.sysEnterprise.unitCreditCodePicUrl = ''
      this.sysEnterprise.fileIds = ''
      this.sysEnterprise.province = ''
      this.sysEnterprise.city = ''
      this.sysEnterprise.status = ''
      this.editFileList = []
      this.fileIdsString = ''
      this.selectedOptions = []
    }
  }
}
</script>

<style>

</style>
